import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:oramemo/entity/device_mine_entity.dart';

import 'blue_logic.dart';

class BlueSettingLogic extends GetxController {
  DeviceMineData? device = Get.arguments;

  final selectedMode = 0.obs; // 0: 自定义模式, 1: 强降噪模式, 2: 室内模式, 3: 室外模式

  // 左右耳音量
  final leftVolume = 3.obs;
  final rightVolume = 3.obs;

  // 左右耳电量
  final leftBattery = 0.obs;
  final rightBattery = 0.obs;

  // 蓝牙连接状态
  final isConnected = false.obs;

  void setMode(int mode) {
    selectedMode.value = mode;
    update();
  }

  void adjustLeftVolume(int value) {
    if (value >= 0 && value <= 5) {
      leftVolume.value = value;
      // 这里可以添加与设备通信的代码
    }
  }

  void adjustRightVolume(int value) {
    if (value >= 0 && value <= 5) {
      rightVolume.value = value;
      // 这里可以添加与设备通信的代码
    }
  }

  bool _hasDialog = false;

  void connectBluetooth() async {
    // 连接蓝牙设备的逻辑
    const remoteId = '06:E5:28:3B:FD:E0';
    BluetoothDevice bluDevice = BluetoothDevice.fromId(remoteId);

    try {
      // 显示连接对话框
      _showConnectingDialog();
      _hasDialog = true;
      await BlueLogic.to.connectToDevice(bluDevice);
      final conDevice = BlueLogic.to.connectedDevice.value;
      isConnected.value =
          conDevice?.remoteId.str == remoteId && conDevice?.isConnected == true;

      // 连接成功后关闭对话框
      if (_hasDialog) {
        Get.back();
      }
    } catch (e) {
      Get.back(); // 关闭连接对话框
      Get.snackbar('连接失败', '请确保设备在范围内并已开启');
    }
  }

  Future<bool?> _showConnectingDialog() {
    return Get.dialog<bool>(
      WillPopScope(
        onWillPop: () async => false, // 防止点击返回键关闭对话框
        child: AlertDialog(
          title: const Text('正在连接设备'),
          content: const Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 16),
              Text('正在尝试连接到设备...'),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                BlueLogic.to.disconnectDevice();

                _hasDialog = false;
                Get.back(result: false);
              },
              child: const Text('取消'),
            ),
          ],
        ),
      ),
      barrierDismissible: false, // 防止点击对话框外部关闭
    );
  }

  void disconnectBluetooth() {
    // 断开蓝牙设备的逻辑
    isConnected.value = false;
  }
}
